/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.Logs;
import entities.Usuarios;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import logica.ColumnsAutoSizer;
import renders.FechaRender;

/**
 *
 * @author root
 */
public class LogsView extends JPanel {

    public static JFrame frame;
    private int altoFrame = 500;
    private Usuarios usuario;

    public LogsView(Usuarios usuario) {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        this.usuario = usuario;
        setearTamañoColumnas();
        setearTamañoFrame();
    }

    public JFrame getFrame() {
        return LogsView.frame;
    }

    private void setFrame(JFrame frame) {
        LogsView.frame = frame;
    }

    private int calcularTamanoTabla() {
        int total = 0;
        for (int column = 0; column < 3; column++) {
            total += masterTable.getColumnModel().getColumn(column).getWidth();
        }
        total += 20;
        return total;
    }

    private void setearTamañoFrame() {
        //Seteo el tamaño del frame respecto al tamaño de la tabla, (489) de alto es por defecto
        frame.setPreferredSize(new Dimension(calcularTamanoTabla(), altoFrame));
    }

    private void setearTamañoColumnas() {
        ColumnsAutoSizer.sizeColumnsToFit(masterTable);
    }

    private void focus() {
        usuarioField.requestFocus();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT l FROM Logs l");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        usuarioLabel = new javax.swing.JLabel();
        fechaLabel = new javax.swing.JLabel();
        observacionesLabel = new javax.swing.JLabel();
        usuarioField = new javax.swing.JTextField();
        observacionesField = new javax.swing.JTextField();
        buscarButton = new javax.swing.JButton();
        fechaDateChooser = new com.toedter.calendar.JDateChooser();
        resultadosLabel = new javax.swing.JLabel();

        FormListener formListener = new FormListener();

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${usuario}"));
        columnBinding.setColumnName("Usuario");
        columnBinding.setColumnClass(entities.Usuarios.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fecha}"));
        columnBinding.setColumnName("Fecha");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${observaciones}"));
        columnBinding.setColumnName("Observaciones");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getColumn(1).setCellRenderer(new FechaRender());

        usuarioLabel.setText("Usuario:");

        fechaLabel.setText("Fecha:");

        observacionesLabel.setText("Observaciones:");

        usuarioField.addKeyListener(formListener);

        observacionesField.addKeyListener(formListener);

        buscarButton.setBackground(new java.awt.Color(1, 154, 210));
        buscarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        buscarButton.setForeground(new java.awt.Color(255, 255, 255));
        buscarButton.setText("Buscar");
        buscarButton.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(resultadosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(176, 176, 176))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(observacionesLabel)
                            .addComponent(fechaLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(usuarioLabel, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(usuarioField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fechaDateChooser, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE)
                            .addComponent(observacionesField))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(buscarButton)
                        .addGap(16, 16, 16))
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 779, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 334, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fechaLabel)
                            .addComponent(fechaDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(usuarioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(usuarioLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(observacionesLabel)
                            .addComponent(observacionesField, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(buscarButton)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(resultadosLabel)
                .addContainerGap())
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.KeyListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == buscarButton) {
                LogsView.this.buscarButtonActionPerformed(evt);
            }
        }

        public void keyPressed(java.awt.event.KeyEvent evt) {
            if (evt.getSource() == usuarioField) {
                LogsView.this.usuarioFieldKeyPressed(evt);
            }
            else if (evt.getSource() == observacionesField) {
                LogsView.this.observacionesFieldKeyPressed(evt);
            }
        }

        public void keyReleased(java.awt.event.KeyEvent evt) {
        }

        public void keyTyped(java.awt.event.KeyEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    private Date setearFechaInicial(Date fecha) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(fecha);
        cal.set(Calendar.AM_PM, Calendar.AM);
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();
    }

    private Date setearFechaFinal(Date fecha) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(fecha);
        cal.set(Calendar.AM_PM, Calendar.PM);
        cal.set(Calendar.HOUR, 11);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        return cal.getTime();
    }

    private void clearCampos() {
        usuarioField.setText("");
        observacionesField.setText("");
        fechaDateChooser.setDate(null);
    }

    @SuppressWarnings("unchecked")
    private void buscarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarButtonActionPerformed
        Query queryTodo;
        Date fechaInicial = null;
        Date fechaFinal = null;
        String usuario = null, observaciones = null;
        queryTodo = entityManager.createNamedQuery("Logs.findByTodo");

        //Si no hay datos en los TextFields ni se eligió una fecha
        if ((usuarioField.getText().equals("")) && (fechaDateChooser.getDate() == null) && (observacionesField.getText().equals(""))) {
            //Mostrar todos los Logs
            list.clear();
            list.addAll(query.getResultList());
            clearCampos();
            //resultadosLabel.setText("Lista restaurada...");
            resultadosLabel.setText("");
            //Sino
        } else {
            //Buscar por los atributos que llenamos/eligimos en la view y luego mostrarlos en la masterTable
            usuario = usuarioField.getText();
            queryTodo.setParameter("usuario", usuario.toUpperCase());
            if (fechaDateChooser.getDate() != null) {
                fechaInicial = setearFechaInicial(fechaDateChooser.getDate());
                fechaFinal = setearFechaFinal(fechaDateChooser.getDate());
            }
            queryTodo.setParameter("fechaInicial", fechaInicial);
            queryTodo.setParameter("fechaFinal", fechaFinal);
            observaciones = observacionesField.getText();
            queryTodo.setParameter("observaciones", observaciones.toUpperCase());
            List<Logs> listaLogsResultado = queryTodo.getResultList();
            list.clear();
            list.addAll(listaLogsResultado);
            resultadosLabel.setText(listaLogsResultado.size() + " resultados.");
        }
    }//GEN-LAST:event_buscarButtonActionPerformed

    private void usuarioFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_usuarioFieldKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            buscarButtonActionPerformed(null);
        }
    }//GEN-LAST:event_usuarioFieldKeyPressed

    private void observacionesFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_observacionesFieldKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            buscarButtonActionPerformed(null);
        }
    }//GEN-LAST:event_observacionesFieldKeyPressed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buscarButton;
    private javax.persistence.EntityManager entityManager;
    private com.toedter.calendar.JDateChooser fechaDateChooser;
    private javax.swing.JLabel fechaLabel;
    private java.util.List<entities.Logs> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JTextField observacionesField;
    private javax.swing.JLabel observacionesLabel;
    private javax.persistence.Query query;
    private javax.swing.JLabel resultadosLabel;
    private javax.swing.JTextField usuarioField;
    private javax.swing.JLabel usuarioLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(Usuarios user) {
        final Usuarios usuario = user;
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LogsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LogsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LogsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LogsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        LogsView.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                frame.setContentPane(new LogsView(usuario));
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Sistema   -   Logs   -   Sistema Integrado de Administración de Alquileres Turísticos  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        if (frame != null) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
